package cn.ailearn.config;

import cn.ailearn.security.filter.JwtAuthenticationTokenFilter;
import cn.ailearn.security.service.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @ClassName SecurityConfig
 * @Description security配置类
 * @Author WDEMO
 * @Date 2025/10/22 15:51
 */
@Configuration
//@EnableWebSecurity// 启用WebSecurity的自动配置，以便Spring Security可以管理Web安全
@EnableGlobalMethodSecurity(prePostEnabled = true)// 启用全局方法安全，允许使用@PreAuthorize和@PostAuthorize注解
public class SecurityConfig {

    @Autowired
    private MyUserDetailsService myUserDetailsService;

    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;

    @Autowired
    private AuthenticationEntryPoint authenticationEntryPoint;

    @Autowired
    private AccessDeniedHandler accessDeniedHandler;



    /**
     * 创建BCryptPasswordEncoder 注入容器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 定义一个名为securityFilterChain的bean，该bean将负责构建和应用安全过滤器链
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 配置HttpSecurity对象，定义安全规则
        http
                .csrf(csrf -> csrf.disable())// 禁用CSRF（跨站请求伪造）保护，因为我们使用的是JWT
                // 授权HTTP请求，定义哪些URL需要什么类型的访问控制
                .authorizeHttpRequests((authz) -> authz
                        // 允许Swagger相关路径匿名访问
                        .requestMatchers( "/swagger-ui/**",
                                "/v3/api-docs/**",
                                "/swagger-resources/**",
                                "/doc.html").permitAll()
                        // 允许"/user/login" URL匿名访问
                        .requestMatchers("/common/user/login","/login").anonymous()

                        // 所有其他请求都需要认证才能访问
                        .anyRequest().authenticated())
                // 添加JWT认证过滤器
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
                // 配置认证失败处理类
                .exceptionHandling(exceptions -> exceptions
                        .authenticationEntryPoint(authenticationEntryPoint)
                        .accessDeniedHandler(accessDeniedHandler))

                // 启用HTTP Basic认证，默认情况下提供简单的用户名/密码认证
                .httpBasic(Customizer.withDefaults());

        http.cors(Customizer.withDefaults());// 启用CORS（跨域资源共享），默认配置

        // 构建并返回SecurityFilterChain
        return http.build();
    }


    @Bean
    public AuthenticationManager authenticationManager(PasswordEncoder passwordEncoder) {

        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        //将编写的UserDetailsService注入进来
        provider.setUserDetailsService(myUserDetailsService);
        //将使用的密码编译器加入进来
        provider.setPasswordEncoder(passwordEncoder);
        //将provider放置到AuthenticationManager 中
        ProviderManager providerManager = new ProviderManager(provider);
        return providerManager;
    }

}
